<?php

/**
 * Pwiff - PHP SWF Library
 *
 * LICENSE
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package    Pwiff
 * @copyright  Copyright (c) 2010 Steven Harris
 * @license    http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @version    $Id: Encoder.php 6 2010-02-17 04:28:26Z indigo.sunrise $
 */

/**
 * Manages the SWF encoding process.
 * 
 * @package Pwiff
 */
class Pwiff_Encoder
{
	/**
	 * Output instance.
	 *
	 * @var Pwiff_Output
	 */
	protected $output;
	
	/**
	 * The Pwiff movie instance.
	 * 
	 * @var Pwiff_Movie
	 */
	protected $movie;
	
	/**
	 * Constructor. Accepts a movie and an output instance.
	 * 
	 * @param  Pwiff_Movie  $movie
	 * @param  Pwiff_Output $output
	 */
	public function __construct(Pwiff_Movie $movie, Pwiff_Output $output)
	{
		$this->movie  = $movie;
		$this->output = $output;
	}
	
	/**
	 * Encodes the movie.
	 */
	public function encode()
	{
		// append the file end tag
		$this->movie->addTag(new Pwiff_Tag_End($this->movie->getEnvironment()));
		
		// encode header and fileattributes
		$this->encodeHeader();
		
		// movie tags
		foreach ($this->movie->getTags() AS $tag) {
			$tag->write($this->output);
		}
	}
	
	/**
	 * Encodes the header.
	 */
	protected function encodeHeader()
	{
		// multiply by 20 for twips
		$frameSize = $this->movie->getFrameSize();
		$frameRect = new Pwiff_Record_Rect($this->movie->getEnvironment());
		$frameRect->setMinX(0)->setMaxX($frameSize[0] * 20)
		          ->setMinY(0)->setMaxY($frameSize[1] * 20);
		
		// we set the file length field later
		$header = new Pwiff_Record_Header($this->movie->getEnvironment());
		$header->setCompressed(false)
		       ->setVersion($this->movie->getEnvironment()->getSwfVersion())
		       ->setFrameSize($frameRect)
		       ->setFrameRate($this->movie->getFrameRate())
		       ->setFrameCount($this->movie->getFrameCount);
		
		// file attributes - TODO: actually support setting the attributes
		$attrs = new Pwiff_Tag_FileAttributes($this->movie->getEnvironment());
		
		// calculate the file length
		$length  = $header->getRecordLength();
		$length += $attrs->getTagLength() + 2; // add 2 for tag header
		
		foreach ($this->movie->getTags() AS $tag) {
			$tagLen = $tag->getTagLength();
			if ($tagLen > 62) {
				$tagLen += 6; // extended header
			}
			else {
				$tagLen += 2; // normal header
			}
			$length += $tagLen;
		}
		
		$header->setFileLength($length);
		
		// write the header and FileAttributes now
		$header->write($this->output);
		$attrs->write($this->output);
	}
}
